<template>
  <div class="form">
    <el-collapse accordion class="el-collapse">
      <el-collapse-item>
        <template slot="title">
          商品管理介绍
        </template>
        <div>商品管理模块可以对客户端的商品进行增删改查等相关操作,来控制客户端商品的列表展示和商品详情</div>
      </el-collapse-item>
    </el-collapse>
    <el-collapse accordion class="el-collapse1">
      <el-collapse-item>
        <template slot="title">
          条件查询
        </template>
        <el-form ref="form" :model="searchForm" label-width="80px" :inline="false" size="small">
          <el-row :gutter="20">
            <el-col :span="6" :offset="0">
              <el-form-item label="商品名称">
                <el-input v-model="searchForm.name" placeholder="商品名称/模糊查询" />
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="商品货号">
                <el-input v-model="searchForm.productSn" placeholder="商品货号" />
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="品牌">
                <el-select v-model="searchForm.brandId " placeholder="商品品牌">
                  <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    @click.native="brandChange"
                  />
                </el-select>

              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="上架状态">
                <el-select v-model="searchForm.publishStatus" placeholder="上架状态">
                  <el-option
                    v-for="item in stateList"
                    :key="item.id"
                    :label="item.state"
                    :value="item.id"
                    @click.native="brandChange"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="审核状态">
                <el-select v-model="searchForm.verifyStatus" placeholder="审核状态">
                  <el-option
                    v-for="item in verifyList"
                    :key="item.id"
                    :label="item.state"
                    :value="item.id"
                    @click.native="brandChange"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="12">
              <el-form-item>
                <el-button @click="onReset">重置</el-button>
                <el-button type="primary" @click="onSearch">搜索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </el-collapse-item>
    </el-collapse>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" size="mini" @click="newAdd">新增</el-button>
        <el-button type="primary" size="mini" @click="excel">导出商品列表excel文件</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="articleList"
        border
        style="width: 100%"
      >
        <el-table-column
          fixed
          label="序号"
          type="index"
          align="center"
          width="100"
        />
        <el-table-column
          label="商品图片"
          width="160"
          align="center"
        >
          <template slot-scope="scope">
            <img :src="scope.row.pic" style="width:100px; height:80px">
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="商品名称"
          align="center"
          width="300"
        >
          <template slot-scope="scope">
            <p>{{ scope.row.name }}</p>
            <p>品牌: {{ scope.row.brandName }}</p>
            <p>{{ scope.row.description }}</p>
          </template>
        </el-table-column>

        <el-table-column
          label="商品价格"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <p>原价: {{ scope.row.originalPrice }}</p>
            <p>现价: {{ scope.row.price }}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="productCategoryName"
          align="center"
          label="商品类别"
          width="100"
        />
        <el-table-column
          label="标签"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.newStatus"
              inactive-text="最新"
              :active-value="1"
              :inactive-value="0"
              @change="changeNew(scope.row)"
            />
            <el-switch
              v-model="scope.row.recommendStatus"
              inactive-text="推荐"
              :active-value="1"
              :inactive-value="0"
              @change="changeYes(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="标签2"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.publishStatus"
              inactive-text="发布"
              :active-value="1"
              :inactive-value="0"
              @change="changeRelease(scope.row)"
            />
            <el-switch
              v-model="scope.row.verifyStatus"
              inactive-text="审核"
              :active-value="1"
              :inactive-value="0"
              @change="changeExamine(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="sku"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <p style="color:#13ce66; font-size:16px" @click="editSku(scope.row.id)">编辑sku</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="weight"
          label="重量"
          align="center"
          width="120"
        />
        <el-table-column
          prop="sort"
          label="排序"
          align="center"
          width="120"
        />
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="180"
        >
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="doDel(scope.row.id)">删除</el-button>
            <el-button type="success" size="mini" @click="goEdit(scope.row.id)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top:20px; text-align:right"
        :current-page="articleObj.start"
        :page-sizes="articleObj.sizes"
        :page-size="articleObj.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="articleObj.totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      title="sku列表"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose"
    >

      <el-button class="positon" type="success" @click="addSkuList">新 增</el-button>

      <el-table v-if="skuList.length > 0" style="padding-top:10px" :data="skuList" border stripe>
        <el-table-column
          type="index"
          label="#"
          fixed
          width="50"
        />
        <el-table-column
          label="图片"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            <el-upload
              class="avatar-uploader"
              action="/lejuAdmin/material/uploadFileOss"
              :headers="{ token }"
              :show-file-list="false"
              :on-success="UploadPictures"
              @click.native="clickSku(scope.row.tempId)"
            >
              <img v-if="scope.row.pic" :src="scope.row.pic" class="miniAvatar">
              <i v-else class="el-icon-plus avatar-uploader-icons" />
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column
          label="颜色"
          width="150"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.color" size="mini" />
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="大小"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.size" size="mini" />
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="库存"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.stock" size="mini" placeholder="自定义库存" />
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="预警库存"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.lowStock" size="mini" placeholder="预警库存" />
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="锁定库存"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.lockStock" size="mini" placeholder="锁定库存" />
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="sku编码"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.skuCode" size="mini" placeholder="sku编码" />
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="价格"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" size="mini" placeholder="价格" />
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="销量"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.sale" size="mini" placeholder="销量" />
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          fixed="right"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button size="default" style="color:red" @click="delSku(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSku">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { productsByPage,
  switchNewStatus,
  switchRecommandStatus,
  switchPublishStatus,
  switchVerifyStatus,
  del as deletes } from '@/api/commdity/list'
import { getToken } from '@/utils/myAuth'
import UUID from 'uuidjs'
import { findAllBrand, productSkusDetail, updateProductAndSkus } from '@/api/commdity/addDetails'
export default {
  data() {
    return {
      dialogVisible: false, // 控制sku列表显示
      skuList: [], // sku列表
      tempSkuId: '', // 临时的skuid,用于确定哪个sku被点击了上传
      stateList: [
        {
          state: '上架',
          id: 1
        },
        {
          state: '未上架',
          id: 0
        }
      ],
      verifyList: [
        {
          state: '审核通过',
          id: 1
        },
        {
          state: '未审核',
          id: 0
        }
      ],
      searchForm: {
        id: ''
      },
      brandList: [],
      value: '',
      loading: false,
      articleObj: {
        limit: 5,
        start: 1,
        totalCount: 0,
        sizes: [5, 10, 15, 20]
      },
      articleList: [], // 商品列表
      sureList: []
    }
  },
  computed: {
    token() {
      return getToken()
    }
  },
  created() {
    this.init()
  },
  mounted() {

  },
  methods: {
    editSku(id) { // 编辑sku
      this.dialogVisible = true
      productSkusDetail(id)
        .then(res => {
          const { message: errMag, data, success } = res
          if (success) {
            data.skus.forEach(element => {
              element.spData = JSON.parse(element.spData)
              element.color = element.spData[0].value
              element.size = element.spData[1].value
            })
            this.skuList = data.skus
            this.sureList = data.product
          } else {
            this.$message.error(errMag)
          }
        })
    },
    addSkuList() { // 点击新增添加skulist
      this.skuList.push(
        {
          color: '',
          size: '',
          lockStock: '', // 锁定库存
          pic: '', // 图片
          sale: '', // 销量
          price: '', // 价格
          skuCode: '', // sku的编码
          lowStock: '', // 预警库存
          stock: '', // 库存
          tempId: UUID.genV4().toString(), // 临时变量,用于删除
          spData: [
            {
              'key': '颜色',
              'value': ''
            },
            {
              'key': '容量',
              'value': ''
            }
          ]
        }
      )
    },
    addSku() { // 点击确定添加sku
      this.skuList.forEach(element => {
        console.log(element)
        element.spData[0].value = element.color
        element.spData[1].value = element.size
        element.spData = JSON.stringify(element.spData)
      })
      var ProductAndSkusVo = {
        pmsSkuStockList: this.skuList,
        product: this.sureList
      }
      updateProductAndSkus(ProductAndSkusVo).then(res => {
        const { message: errMag, success } = res
        if (success) {
          this.$message.success('编辑sku列表成功')
          this.dialogVisible = false
        } else {
          this.$message.error(errMag)
        }
      })
    },
    delSku(id) { // 删除一列sku
      var item = this.skuList.find(el => el.id === id)
      var index = this.skuList.findIndex(el => el === item)
      this.$confirm('此操作将会删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.skuList.splice(index, 1)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleClose() { // 点击x关闭sku列表
      this.dialogVisible = false
    },
    clickSku(id) {
      this.tempSkuId = id
    },
    UploadPictures(res, file) { // 上传sku图片成功函数
      var temp = this.skuList.find(ele => ele.tempId === this.tempSkuId)

      const { success, data } = res
      if (success) {
        const { fileUrl } = data
        temp.pic = fileUrl
        console.log(temp.pic)
      }
    },
    onReset() { // 重置
      this.searchForm = {}
      this.init()
    },
    brandChange() { // 商品品牌下拉框改变时触发
      this.searchForm.brandName = this.brandList.find(ele => ele.id === this.searchForm.brandId).name
    },
    changeNew(params) { // 最新
      switchNewStatus({
        productId: params.id,
        status: params.newStatus
      }).then(res => {
        const { message: errMag, success } = res
        if (success) {
          this.$message.success('更新状态成功')
        } else {
          this.$message.error(errMag)
        }
      })
    },
    changeYes(params) { // 推荐
      switchRecommandStatus({
        productId: params.id,
        status: params.recommendStatus
      }).then(res => {
        const { message: errMag, success } = res
        if (success) {
          this.$message.success('更新状态成功')
        } else {
          this.$message.error(errMag)
        }
      })
    },
    changeRelease(params) { // 发布
      switchPublishStatus({
        productId: params.id,
        status: params.publishStatus
      }).then(res => {
        const { message: errMag, success } = res
        if (success) {
          this.$message.success('更新状态成功')
        } else {
          this.$message.error(errMag)
        }
      })
    },

    changeExamine(params) { // 审核
      switchVerifyStatus({
        productId: params.id,
        status: params.verifyStatus
      }).then(res => {
        const { message: errMag, success } = res
        if (success) {
          this.$message.success('更新状态成功')
        } else {
          this.$message.error(errMag)
        }
      })
    },
    init() {
      this.loading = true
      const { start, limit } = this.articleObj
      productsByPage(start, limit, this.searchForm).then(
        res => {
          const { success, data, message: errMge } = res
          if (success) {
            const { rows, total } = data
            this.articleList = rows
            console.log(this.articleList)
            this.articleObj.totalCount = total
          } else {
            this.$message.error(errMge)
          }
          this.loading = false
        }
      )
      findAllBrand().then(res => {
        const { data, message: errMge, success } = res
        if (success) {
          const { items } = data
          this.brandList = items
        } else {
          this.$message.error(errMge)
        }
      })
    },

    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.articleObj.limit = val
      this.init()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.articleObj.start = val
      this.init()
    },
    doDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletes(id).then(res => {
          this.init()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
      })
    },
    goEdit(id) {
      this.$router.push({ name: 'commodityEdit', params: { id: id }})
    },
    handleClick(row) {
      console.log(row)
    },
    newAdd() {
      this.$router.push({ name: 'commodityAdd' })
    },
    excel() {

    },
    onSearch() { // 搜索
      // 获取商品id
      // this.searchForm.id = this.articleList.find(ele => ele.name === this.searchForm.name).id
      console.log(this.searchForm)
      this.articleObj.start = 1
      this.init()
    }
  }
}
</script>

<style scoped lang="scss">
    .form{
        background-color: #f0f2f5;
        .el-collapse{
            padding: 10px;
            background-color: #fff;
        }
        .el-collapse1{
            margin: 30px;
            padding: 10px;
        }
        .box-card{
            margin:0px 30px;
        }
         .miniAvatar {
    width: 100px;
    height: 100px;
    display: block;
  }
    }
    .positon{
     float: right;
     margin-bottom: 20px;
    }
</style>
